package com.example.question.bt.backtrack1;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2023-07-16
 * @Author Jonathan
 */
public class Code05_39 {

    public static void main(String[] args) {
        Code05_39 code = new Code05_39();
        System.out.println(code.combinationSum(new int[]{2, 3, 5}, 8));
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(candidates, 0, 0, path, res, target);
        return res;
    }

    private void dfs(int[] candidates, int sum, int start, List<Integer> paths, List<List<Integer>> res, int target) {
        if (sum == target) {
            res.add(new ArrayList<>(paths));
            return;
        }
        if (sum > target) {
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            sum += candidates[i];
            paths.add(candidates[i]);
            dfs(candidates, sum, i, paths, res, target);
            sum -= candidates[i];
            paths.remove(paths.size() - 1);
        }

    }
}
